﻿using System;
using System.Collections.Generic;
using System.Text;

namespace IETTortak
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.SqlClient;
    using System.IO;
    using System.Runtime.CompilerServices;
    using System.Security.Cryptography;
    using System.Text;
    using System.Windows.Forms;

    public class DAL
    {
        private static SqlCommand buildQuery(string strCmd, bool isSP, SqlConnection sqlConn, params object[] pars)
        {
            if ((strCmd == null) | (strCmd.Length == 0))
            {
                throw new ArgumentNullException("strCmd", "SQL command string cannot be empty.");
            }
            if ((pars.Length % 2) != 0)
            {
                throw new ArgumentException("Number of variable arguments must be a multiple of 2.");
            }
            SqlCommand command2 = new SqlCommand(strCmd, sqlConn);
            if (isSP)
            {
                command2.CommandType = CommandType.StoredProcedure;
            }
            int num2 = pars.Length - 1;
            for (int i = 0; i <= num2; i += 2)
            {
                if (pars[i + 1] == null)
                {
                    pars[i + 1] = DBNull.Value;
                }
                command2.Parameters.AddWithValue(pars[i].ToString(), RuntimeHelpers.GetObjectValue(pars[i + 1]));
            }
            return command2;
        }


        public static string Decrypt(string strText, string sDecrKey)
        {
            byte[] rgbKey = new byte[0];
            byte[] rgbIV = new byte[] { 0x12, 0x34, 0x56, 120, 0x90, 0xab, 0xcd, 0xef };
            byte[] buffer = new byte[strText.Length + 1];
            rgbKey = Encoding.UTF8.GetBytes(sDecrKey.Substring(0, 8));
            DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
            buffer = Convert.FromBase64String(strText);
            MemoryStream stream2 = new MemoryStream();
            CryptoStream stream = new CryptoStream(stream2, provider.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
            stream.Write(buffer, 0, buffer.Length);
            stream.FlushFinalBlock();
            return Encoding.UTF8.GetString(stream2.ToArray());
        }

        public static string DecryptText(string strText)
        {
            string str2 = Decrypt(strText, ".&%#@?,:*");
            if (!str2.EndsWith("iett?'^3+vr&w"))
            {
                throw new InvalidOperationException("Do not mess with the encryption internals.");
            }
            return str2.Substring(0, str2.Length - 15);
        }

        private static string Encrypt(string strText, string strEncrKey)
        {
            byte[] rgbKey = new byte[0];
            byte[] rgbIV = new byte[] { 0x12, 0x34, 0x56, 120, 0x90, 0xab, 0xcd, 0xef };
            rgbKey = Encoding.UTF8.GetBytes(strEncrKey.Substring(0, 8));
            DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
            byte[] bytes = Encoding.UTF8.GetBytes(strText);
            MemoryStream stream2 = new MemoryStream();
            CryptoStream stream = new CryptoStream(stream2, provider.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
            stream.Write(bytes, 0, bytes.Length);
            stream.FlushFinalBlock();
            return Convert.ToBase64String(stream2.ToArray());
        }

        public static string EncryptText(string strText)
        {
            return Encrypt(strText + "iett?'^3+vr&w", ".&%#@?,:*");
        }

        public static void ExecBindComboBox(ref ComboBox cmb, string ValueMember, string DisplayMember, string strSQL)
        {
            try
            {
                cmb.DataSource = GetDataTable("combo", strSQL, new object[0]);
                cmb.DisplayMember = DisplayMember;
                cmb.ValueMember = ValueMember;
            }
            catch (Exception)
            {
            }
        }

        public static Dictionary<string, object> ExecNonQuery(string strSql, bool isSP, params object[] pars)
        {
            SqlConnection sqlConn = new SqlConnection(GetConnectionString());
            sqlConn.Open();
            SqlCommand command = buildQuery(strSql, isSP, sqlConn, pars);
            Dictionary<string, object> dictionary2 = new Dictionary<string, object>();
            command.ExecuteNonQuery();
            sqlConn.Close();

            foreach (SqlParameter parameter in command.Parameters)
            {
                if ((parameter.Direction == ParameterDirection.Output) | (parameter.Direction == ParameterDirection.InputOutput))
                {
                    dictionary2.Add(parameter.ParameterName, RuntimeHelpers.GetObjectValue(parameter.Value));
                }
            }

            return dictionary2;
        }

        public static object ExecScalar(string strSql, bool isSP, params object[] pars)
        {
            SqlConnection sqlConn = new SqlConnection(GetConnectionString());
            sqlConn.Open();
            object objectValue = buildQuery(strSql, isSP, sqlConn, pars).ExecuteScalar();
            sqlConn.Close();
            return objectValue;
        }

        public static string GetConnectionString()
        {
            //return @"Data Source=JACK\XENON;Initial Catalog=PublicTransport;Integrated Security=True";
            return @"Data Source=JACK\XENON;Initial Catalog=PublicTransport;Integrated Security=False;uid=iett;password=13tt50r";
        }

        public static DataTable GetDataTable(string tableName, string strSql, params object[] pars)
        {
            return GetDataTable(tableName, false, strSql, pars);
        }

        public static DataTable GetDataTable(string tableName, bool isSP, string strSql, params object[] pars)
        {
            DataTable table2;
            SqlConnection connection = new SqlConnection(GetConnectionString());
            SqlCommand selectCommand = new SqlCommand(strSql, connection);
            if ((pars.Length % 2) != 0)
            {
                throw new ArgumentException("Number of variable arguments must be a multiple of 2.");
            }
            int num2 = pars.Length - 1;
            for (int i = 0; i <= num2; i += 2)
            {
                selectCommand.Parameters.AddWithValue(pars[i].ToString(), RuntimeHelpers.GetObjectValue(pars[i + 1]));
            }
            
            if (isSP)
                selectCommand.CommandType = CommandType.StoredProcedure;

            SqlDataAdapter adapter = new SqlDataAdapter(selectCommand);
            DataTable dataTable = new DataTable();
            try
            {
                connection.Open();
                adapter.Fill(dataTable);
                dataTable.TableName = tableName;
                table2 = dataTable;
            }
            catch (Exception ex)
            {
                table2 = new DataTable();
            }
            finally
            {
                connection.Close();
                selectCommand.Dispose();
                connection.Dispose();
            }
            return table2;
        }

        public static string GetPasswordHashed(string password, string salt)
        {
            MD5CryptoServiceProvider provider = new MD5CryptoServiceProvider();
            provider.Initialize();
            return Convert.ToBase64String(provider.ComputeHash(Encoding.UTF8.GetBytes(password + salt)));
        }

        public static string GetRandomSalt()
        {
            Random random = new Random();
            byte[] buffer = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
            random.NextBytes(buffer);
            return Convert.ToBase64String(buffer).Substring(0, 10);
        }

        public static SqlCommand GetSqlCommand(string strSql, params object[] pars)
        {
            SqlConnection connection = new SqlConnection(GetConnectionString());
            SqlCommand command = new SqlCommand(strSql, connection);
            if ((pars.Length % 2) != 0)
            {
                throw new ArgumentException("Number of variable arguments must be a multiple of 2.");
            }
            int num2 = pars.Length - 1;
            for (int i = 0; i <= num2; i += 2)
            {
                if (pars[i + 1] == null)
                {
                    pars[i + 1] = DBNull.Value;
                }
                command.Parameters.AddWithValue(pars[i].ToString(), RuntimeHelpers.GetObjectValue(pars[i + 1]));
            }
            return command;
        }

        //private static string LoadFormStatePersistence(string FormName, string FieldName)
        //{
        //    return LoadFormStatePersistence(FormName, FieldName, 0);
        //}

        //private static string LoadFormStatePersistence(string FormName, string FieldName, int IDFilter)
        //{
        //    return Conversions.ToString(ExecScalar("SELECT PersistencyData FROM UI.FormStatePersistence WHERE Username = @username AND FieldName = @fieldname AND IDFilter = @idfilter", false, new object[] { "@username", Environment.UserName, "@fieldname", FieldName, "@idfilter", IDFilter }));
        //}

        //private static void SaveFormStatePersistence(string FormName, string FieldName, string PersistencyData)
        //{
        //    SaveFormStatePersistence(FormName, FieldName, 0, PersistencyData);
        //}

        //private static void SaveFormStatePersistence(string FormName, string FieldName, int IDFilter, string PersistencyData)
        //{
        //    int num = Conversions.ToInteger(ExecScalar("SELECT FormStatePersistenceID FROM UI.FormStatePersistence WHERE Username=@Username AND FormName = @FormName AND FieldName = @FieldName AND IDFilter = @IDFilter", false, new object[] { "@Username", Environment.UserName, "@FormName", FormName, "@FieldName", FieldName, "@IDFilter", IDFilter }));
        //    if (num > 0)
        //    {
        //        ExecNonQuery("UPDATE UI.FormStatePersistence SET PersistencyData = @PersistencyData WHERE FormStatePersistenceID = @id", false, new object[] { "@id", num, "@PersistencyData", PersistencyData });
        //    }
        //    else
        //    {
        //        ExecNonQuery("INSERT INTO UI.FormStatePersistence (Username, FormName, FieldName, IDFilter, PersistencyData ) VALUES ( @Username, @FormName, @FieldName, @IDFilter, @PersistencyData )", false, new object[] { "@Username", Environment.UserName, "@FormName", FormName, "@FieldName", FieldName, "@IDFilter", IDFilter, "@PersistencyData", PersistencyData });
        //    }
        //}
    }
}
